package com.xuedongzhilian.controller;

import com.xuedongzhilian.dto.Result;
import com.xuedongzhilian.dto.StudyPlanDTO;
import com.xuedongzhilian.entity.*;
import com.xuedongzhilian.service.*;
import com.xuedongzhilian.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 个人成长看板控制器
 * </p>
 *
 * @author 学动智联团队
 * @since 2025-10-14
 */
@Slf4j
@RestController
@RequestMapping("/growth-dashboard")
public class GrowthDashboardController {

    @Resource
    private IGrowthDataService growthDataService;
    
    @Resource
    private ISubTaskService subTaskService;
    
    @Resource
    private IGoalService goalService;
    
    @Resource
    private ICheckInService checkInService;
    
    @Resource
    private IRunningRecordService runningRecordService;
    
    @Resource
    private IStudyPlanService studyPlanService;

    /**
     * 获取个人成长看板概览
     */
    @GetMapping("/overview")
    public Result getGrowthOverview() {
        Long userId = UserHolder.getUser().getId();
        
        // 获取今日数据
        LocalDate today = LocalDate.now();
        
        // 今日学习打卡次数
        Integer todayStudyCheckIns = checkInService.lambdaQuery()
                .eq(CheckIn::getUserId, userId)
                .eq(CheckIn::getType, 1) // 学习打卡
                .eq(CheckIn::getCheckInDate, today)
                .count();
        
        // 今日运动打卡次数
        Integer todaySportCheckIns = checkInService.lambdaQuery()
                .eq(CheckIn::getUserId, userId)
                .eq(CheckIn::getType, 2) // 运动打卡
                .eq(CheckIn::getCheckInDate, today)
                .count();
        
        // 今日跑步记录
        List<RunningRecord> todayRunningRecords = runningRecordService.lambdaQuery()
                .eq(RunningRecord::getUserId, userId)
                .ge(RunningRecord::getStartTime, today.atStartOfDay())
                .le(RunningRecord::getStartTime, today.atTime(23, 59, 59))
                .list();
        
        // 未完成的支线任务数量
        Integer pendingSubTasks = subTaskService.lambdaQuery()
                .eq(SubTask::getUserId, userId)
                .eq(SubTask::getStatus, 1) // 未完成
                .count();
        
        // 进行中的目标数量
        Integer ongoingGoals = goalService.lambdaQuery()
                .eq(Goal::getUserId, userId)
                .eq(Goal::getStatus, 1) // 进行中
                .count();
        
        // 构造概览数据
        Map<String, Object> overview = new HashMap<>();
        overview.put("todayStudyCheckIns", todayStudyCheckIns);
        overview.put("todaySportCheckIns", todaySportCheckIns);
        overview.put("todayRunningRecords", todayRunningRecords);
        overview.put("pendingSubTasks", pendingSubTasks);
        overview.put("ongoingGoals", ongoingGoals);
        
        return Result.ok(overview);
    }

    /**
     * 获取成长统计数据
     */
    @GetMapping("/statistics")
    public Result getGrowthStatistics(@RequestParam(required = false) Integer days) {
        Long userId = UserHolder.getUser().getId();
        
        // 默认获取最近30天的数据
        if (days == null) {
            days = 30;
        }
        
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days - 1);
        
        // 获取成长数据
        List<GrowthData> growthDataList = growthDataService.lambdaQuery()
                .eq(GrowthData::getUserId, userId)
                .ge(GrowthData::getDate, startDate)
                .le(GrowthData::getDate, endDate)
                .orderByAsc(GrowthData::getDate)
                .list();
        
        // 获取学习计划完成情况
        // 注意：IStudyPlanService没有继承IService，所以不能使用lambdaQuery()
        List<StudyPlanDTO> studyPlanDTOs = studyPlanService.getStudyPlansByUserId(userId);
        List<StudyPlan> studyPlans = studyPlanDTOs.stream()
                .map(dto -> {
                    StudyPlan plan = new StudyPlan();
                    org.springframework.beans.BeanUtils.copyProperties(dto, plan);
                    return plan;
                })
                .filter(plan -> plan.getCreateTime() != null && 
                        plan.getCreateTime().toLocalDate().compareTo(startDate) >= 0 && 
                        plan.getCreateTime().toLocalDate().compareTo(endDate) <= 0)
                .collect(java.util.stream.Collectors.toList());
        
        // 统计学习计划完成率
        long totalPlans = studyPlans.size();
        long completedPlans = studyPlans.stream()
                .filter(plan -> plan.getStatus() != null && plan.getStatus() == 2)
                .count();
        
        double completionRate = totalPlans > 0 ? (double) completedPlans / totalPlans * 100 : 0;
        
        // 构造统计数据
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("growthDataList", growthDataList);
        statistics.put("totalStudyPlans", totalPlans);
        statistics.put("completedStudyPlans", completedPlans);
        statistics.put("completionRate", String.format("%.1f", completionRate));
        
        return Result.ok(statistics);
    }

    /**
     * 获取今日任务提醒
     */
    @GetMapping("/today-reminders")
    public Result getTodayReminders() {
        Long userId = UserHolder.getUser().getId();
        LocalDate today = LocalDate.now();
        
        // 获取今日待完成的支线任务
        List<SubTask> todaySubTasks = subTaskService.lambdaQuery()
                .eq(SubTask::getUserId, userId)
                .eq(SubTask::getStatus, 1) // 未完成
                .le(SubTask::getDueDate, today)
                .orderByAsc(SubTask::getDueDate)
                .list();
        
        // 获取截止日期为今天的长期目标
        List<Goal> todayGoals = goalService.lambdaQuery()
                .eq(Goal::getUserId, userId)
                .eq(Goal::getStatus, 1) // 进行中
                .eq(Goal::getEndDate, today)
                .list();
        
        // 构造提醒数据
        Map<String, Object> reminders = new HashMap<>();
        reminders.put("subTasks", todaySubTasks);
        reminders.put("goals", todayGoals);
        
        return Result.ok(reminders);
    }
}